package com.yc.cloud.sms.sevice.impl;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.yc.cloud.sms.config.AliyunSmsProperties;
import com.yc.cloud.sms.dto.SmsParam;
import com.yc.cloud.sms.response.SmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import cn.hutool.json.JSONUtil;

@Slf4j
@Service("aliyunSmsService")
public class AliyunSmsServiceImpl extends AbstractSmsService {

    @Resource
    private AliyunSmsProperties aliyunSmsProperties;

    private volatile Client client;

    /**
     * 创建阿里云短信客户端（单例模式）
     */
    private Client getClient() throws Exception {
        if (client == null) {
            synchronized (this) {
                if (client == null) {
                    Config config = new Config()
                            .setAccessKeyId(aliyunSmsProperties.getAccessKeyId())
                            .setAccessKeySecret(aliyunSmsProperties.getAccessKeySecret());
                    // 访问的域名
                    config.endpoint = "dysmsapi.aliyuncs.com";
                    client = new Client(config);
                }
            }
        }
        return client;
    }

    @Override
    protected SmsResponse doSend(SmsParam param) {
        try {
            Client client = getClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(param.getMobile())
                    .setSignName(aliyunSmsProperties.getSignName())
                    .setTemplateCode(param.getTemplateId());

            // 如果有模板参数，转换为JSON字符串
            if (param.getTemplateParams() != null && param.getTemplateParams().length > 0) {
                // 将数组转换为键值对格式，例如：{"code":"123456"}
                var paramMap = new java.util.HashMap<String, String>();
                // 假设模板参数的第一个值是验证码
                paramMap.put("code", param.getTemplateParams()[0]);
                sendSmsRequest.setTemplateParam(JSONUtil.toJsonStr(paramMap));
            }

            // 发送短信
            SendSmsResponse response = client.sendSms(sendSmsRequest);
            SendSmsResponseBody body = response.getBody();

            // 判断是否发送成功
            if (body != null && "OK".equalsIgnoreCase(body.getCode())) {
                log.info("短信发送成功, BizId: {}", body.getBizId());
                return SmsResponse.builder().success(true).build();
            }

            // 发送失败，记录错误信息
            log.error("阿里云短信发送失败: code={}, message={}, requestId={}",
                    body.getCode(), body.getMessage(), body.getRequestId());
            return SmsResponse.builder().success(false).errorCode(body.getCode()).errorMessage(body.getMessage())
                    .build();

        } catch (Exception e) {
            log.error("阿里云短信发送异常", e);
            return SmsResponse.builder().success(false).errorCode("500").errorMessage(e.getMessage()).build();
        }
    }

    @Override
    public String getProvider() {
        return "aliyun";
    }
}